<!-- 生产报工页面 -->
<template>
	<view>
		<newNavBar rightCustomPrefix="iconfont" :rightIcon="rightIcon" @clikeRight="saveBgInfo"></newNavBar>
		<view style="">
			<view class="content" style="padding-top: 0px;background-color: #fff;">
				<uni-forms ref="baseForm" :modelValue="baseFormData" label-position="top">
					<!-- <uni-forms-item label="派工单编码" name="pgCode" :labelWidth="labelWidth" required>
						<view class="form-item">
							<uni-easyinput type="text" v-model="baseFormData.pgCode" placeholder="请输入派工单编码" />
							<uni-icons type="scan" size="27" style="margin-left: 6px;" @click="iconClick" />
						</view>
					</uni-forms-item> -->
					<uni-forms-item :label="referLabel" name="pgCode" :labelWidth="labelWidth" required>
						<view class="form-item">
							<uni-easyinput v-model="baseFormData.pgCode" placeholder="请选择" disabled
								:styles="{'disableColor':'#fff'}" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="合格数" name="number" :labelWidth="labelWidth" required>
						<uni-easyinput type="number" v-model="baseFormData.number" placeholder="请输入合格数" />
					</uni-forms-item>
					<uni-forms-item label="不合格数" name="disNumber" :labelWidth="labelWidth" required>
						<uni-easyinput type="number" v-model="baseFormData.disNumber" placeholder="请输入不合格数" />
					</uni-forms-item>

					<uni-forms-item label="发生日期" name="happenDate" :labelWidth="labelWidth" required>
						<uni-datetime-picker type="date" :clear-icon="false" v-model="baseFormData.happenDate" />
					</uni-forms-item>
				</uni-forms>

			</view>

			<view style="margin-top: 10px;background-color: #ffffff;">
				<uni-section style="padding: 0px;" :typeColor="mainColor" type="line" titleColor="#000"
					titleFontSize="17px" title="人员报工信息">

					<template v-slot:right>
						<view style="padding-right: 5px;" @click="addUserInfo">
							<uni-icons customPrefix="iconfont" :color="mainColor" :size="30"
								type="layui-icon-add-circle"></uni-icons>
						</view>
					</template>

					<view style="padding: 0px 10px 10px 10px;">
						<view v-for="(listItem,index) in listInfo" :index="index" :key="index" style="margin-top: 6px;"
							@longpress="longDelItem(index)">
							<view style="margin:0px 0px 15px 0px;">
								<uni-list-item :border="false" direction="column"
									:style="{'border-radius': '7px','box-shadow': '0 1px 6px '+ shadowColor}">
									<template v-slot:body>
										<view style="background-color: #ffffff;">
											<uni-row v-for="(litem,rindex) in listItem.list" :key="rindex">
												<uni-col v-for="(citem,cindex) in litem.content" :key="cindex"
													:span="getListContent(litem.content)">
													<view v-if="citem.type=='input'" style="padding: 5px; ">
														<text>{{citem.title}}: </text>
														<uni-easyinput type="text"
															v-model="userInfoList[index][citem.code]"
															placeholder="请输入数值" />
													</view>
													<view v-else style="padding: 5px;">
														<text>{{citem.title}}: </text>
														<text style="color: #686765;">{{citem.value}}</text>
													</view>
												</uni-col>
											</uni-row>
										</view>
									</template>
								</uni-list-item>
							</view>
						</view>
					</view>
				</uni-section>
			</view>
		</view>
	</view>
	<uni-popup ref="alertDialog" type="dialog">
		<commonDiaog></commonDiaog>
	</uni-popup>

</template>

<script>
	import * as SystemJs from '../../common/system.js'
	import * as configJs from '../../common/config.js'
	export default {
		data() {
			return {
				pageCode: '',
				pageType: '',
				mainColor: '',
				shadowColor: '#7c7c7c',
				//添加报工数据信息
				baseFormData: {
					pgCode: '',
					number: '0',
					disNumber: '0',
					happenDate: '',
					groupCode: '', //班组编码
					gxCode: '', //工序编码
					parentGx: '', //工序大类编码
					plType: '' //计划类型编码
				},
				current: 0,
				items: [],
				labelWidth: 80,
				rightIcon: 'layui-icon-ok',
				//滑动区域的高度(单位px)
				swiperHeight: 0,
				windowWidth: 0,
				StatusBar: 0,
				listInfo: [], //显示的用户信息列表（只做显示用）
				//悬浮按钮进行移动
				x: 0,
				y: 0,
				//悬浮按钮的样式设置
				pattern: {
					color: '#000',
					backgroundColor: '#fff',
					selectedColor: '#000',
					buttonColor: configJs.baseColor.mainTitleColor,
					iconColor: '#fff'
				},
				infoHead: [
					[{
						code: 'userCode',
						name: '人员编码'
					}, {
						code: 'userName',
						name: '人员名称'
					}],
					[{
						code: 'yNum',
						name: '合格数',
						type: 'input'
					}, {
						code: 'nNum',
						name: '不合格数',
						type: 'input'
					}]
				],
				userInfo: {
					userCode: '', //用户编码
					userName: '', //用户名称
					yNum: '0', //合格数
					nNum: '0' //不合格数
				},
				userInfoList: [], //用户信息列表
				referType: '', //参照类型pg(派工单)，bg(报工单)
				referLabel: '派工单编码', //参照单据编码的名称
				noClick: true,
				
				deviceCode:'',

			}
		},
		onLoad(res) {
			this.pageCode = res.pageCode;
			
			//获取传输的对象
			if (res.obj && !SystemJs.systemJs.IsEmpty(JSON.stringify(res.obj))) {
				var transObj = JSON.parse(res.obj);
				this.baseFormData.pgCode = transObj.pgCode;
				this.baseFormData.groupCode = transObj.groupCode;
				this.baseFormData.parentGx = transObj.parentGx;
				this.baseFormData.plType = transObj.plType;
				this.deviceCode = transObj.deviceCode;
				if (!SystemJs.systemJs.IsEmpty(transObj.yNum)) {
					this.baseFormData.number = transObj.yNum;
				}
			}
			//创建报工记录是参照的报工单(bg)还是派工单(pg)
			if (res.referType && !SystemJs.systemJs.IsEmpty(JSON.stringify(res.referType))) {
				this.referType = res.referType;
				if (this.referType == "bg") {
					this.referLabel = "报工单编码";
				}
			}
			SystemJs.systemJs.showTitleBar("添加报工记录", true)
			this.mainColor = configJs.baseColor.mainTitleColor;
			//设置默认日期
			this.baseFormData.happenDate = SystemJs.systemJs.getDate()
			this.items = ['生产报工列表', '添加报工'];
			//获取屏幕高度
			uni.getSystemInfo({
				success: (res) => {
					this.y = res.windowHeight
					this.windowWidth = res.windowWidth;
					var statusBar = res.statusBarHeight //状态栏高度
					//屏幕高度-状态栏高度-自定义导航栏高度
					this.swiperHeight = res.screenHeight - statusBar - 45
					this.StatusBar = statusBar
					console.log('heightShow', this.swiperHeight)
				}
			})

			var list = [{
				userCode: 'admin1',
				userName: '管理员',
				number: '123',
				disNumber: '300'
			}, {
				userCode: 'admin2',
				userName: '管理员',
				number: '123',
				disNumber: '300'
			}];
			// this.getList(list);
		},
		methods: {
			getList(list) {
				this.listInfo = this.createListItemInfo(this.infoHead, list);
			},
			//获取列表内容中每行的个数
			getListContent(content) {
				var count = 0;
				if (content.length > 0) {
					count = 24 / content.length
				}
				return count;
			},

			//点击导航
			onClickItem(e) {
				if (this.current != e.currentIndex) {
					this.current = e.currentIndex;
					if (this.current == 1) {
						this.rightIcon = ''
					} else {
						this.rightIcon = 'icon-shaixuan';
					}
				}
			},
			//点击扫描按钮
			iconClick(type) {
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: (res) => {

						console.log("e:", res.result);
					},
					fail: (err) => {
						console.log("e:", err);
						// SystemJs.httpUnit.uniToast(JSON.stringify(err));
					}
				})
			},
			//打开日期选择器
			open() {
				this.$nextTick(() => {
					this.$refs.happenDate.open();
				})
			},
			//选择日期确认事件
			confirm(e) {
				console.log(e);
				try {
					this.baseFormData.happenDate = e.fulldate
				} catch (e) {
					console.log(e);
				}
			},


			//打开控件窗体
			openRefs(e) {
				this.$nextTick(() => {
					this.$refs[e].open()
				})
			},
			//关闭控件窗体
			closeRefs(e) {
				this.$refs[e].close()
			},
			/**
			 * 保存报工记录
			 */
			saveBgInfo() {

				// SystemJs.httpUnit.uniToast("232")


				// SystemJs.httpUnit.uniToast(JSON.stringify(this.userInfoList))
				var num = 0; //合格数
				var disNum = 0; //不合格数
				var datas = []; //传输的人员信息列表
				if (this.userInfoList == undefined || this.userInfoList.length < 1) {
					SystemJs.httpUnit.uniToast("请先选择报工人员")
					return;
				}
				for (var i = 0; i < this.userInfoList.length; i++) {
					var obj = this.userInfoList[i]
					obj.createuser = configJs.getBaseInfo.getUserInfo().userCode
					if (SystemJs.systemJs.IsEmpty(obj.yNum) || !isFinite(Number(obj.yNum))) {
						SystemJs.httpUnit.uniToast(`${obj.userName}:的合格数录入不正确`)
						return;
					}
					if (SystemJs.systemJs.IsEmpty(obj.nNum) || !isFinite(Number(obj.nNum))) {
						SystemJs.httpUnit.uniToast(`${obj.userName}:的不合格数录入不正确`)
						return;
					}
					if (Number(obj.yNum) <= 0 && Number(obj.nNum) <= 0) {
						SystemJs.httpUnit.uniToast(`${obj.userName}:的合格数和不合格数不能同时为0`)
						return;
					}
					num += Number(obj.yNum);
					disNum += Number(obj.nNum);
					//合并对象数据
					Object.assign(obj, this.baseFormData)
					if (this.referType == "bg") {
						obj.bgCode = this.baseFormData.pgCode;
					}
					datas.push(obj);
				}
				if (num > Number(this.baseFormData.number)) {
					SystemJs.httpUnit.uniToast("人员合格总数与录入的合格数不相同")
					return;
				}
				if (disNum > Number(this.baseFormData.disNumber)) {
					SystemJs.httpUnit.uniToast("人员不合格总数与录入的不合格数不相同")
					return;
				}
				console.log( JSON.stringify(datas))
				SystemJs.unitJs.noMultipleClicks(this, () => {
					var obj = {};
					obj = SystemJs.systemJs.copyObject(this.baseFormData);
					obj.datas = datas;
					obj.deviceCode = this.deviceCode;
					obj.referType = this.referType;
					
					SystemJs.httpUnit.requestCryptoPost({
						url: 'MachineWorkReport/Save_Machine_WorkReport',
						data: obj,
						isLoading: true
					}).then((res) => {
						if (res.Result) {
							SystemJs.httpUnit.uniToast("保存成功");
							this.baseFormData.pgCode = "";
							this.userInfoList = [];
							this.listInfo = [];
							let canNavBack = getCurrentPages()
							if (canNavBack && canNavBack.length > 1) {
								uni.navigateBack({
									delta: 1
								})
							} else {
								//如果刷新页面当前页面的路由信息会丢失，所以只能通过原生js的方法退回上一页面
								history.back();
							}
						} else {
							SystemJs.httpUnit.uniToast(res.Message)
						}
					}).catch((err) => {
						SystemJs.httpUnit.uniToast(JSON.stringify(err))
					})
				})
			},
			///长按人员删除事件
			longDelItem(index) {
				var data = this.listInfo[index];
				var obj = SystemJs.showDialog.dialogInfo
				obj.msgType = "warn";
				obj.title = "提示";
				obj.content = "确定要删除吗？";
				obj.cancel = true;
				obj.confirm = true;
				obj.dialogConfirm(() => {
					this.listInfo.splice(index, 1)
					this.userInfoList.splice(index, 1)
				})
				obj.dialogClose(() => {

				})
				SystemJs.showDialog.openDialog(this.$refs.alertDialog, obj)
			},
			/**
			 * 选择派工单信息
			 */
			selectPGDInfo() {
				///打开参照列表
				var title = "派工单列表";
				uni.navigateTo({
					url: `/pages/business/CommonInfo?pageCode=${this.pageCode}&dataType=pgd&title=${title}`,
				});
				//监听该事件是否被处罚，此方法只监听一次
				uni.$once('saveData', this.updateSaveData)
			},
			/**
			 * 添加人员信息
			 */
			addUserInfo() {

				///打开参照列表
				var title = "人员信息";
				var obj = {};
				obj.groupCode = this.baseFormData.groupCode;
				obj.parentGx = this.baseFormData.parentGx;
				obj.plType = this.baseFormData.plType;
				var objStr = JSON.stringify(obj);
				
				uni.navigateTo({
					url: `/pages/business/CommonInfo?pageCode=${this.pageCode}&dataType=user&title=${title}&obj=${objStr}`,
				});
				//监听该事件是否被处罚，此方法只监听一次
				uni.$once('saveData', this.updateSaveData)
			},
			updateSaveData(res) {
				
				if (this.pageCode == "prbg" && res.value != undefined) {
					if (res.dataType == "user") {
						var listValue = [];
						listValue = res.value;
						this.addUserInfoList(listValue)
					}
					if (res.dataType == "pgd") {
						var listValue = [];
						listValue = res.value;
						if (listValue.length > 0) {
							this.baseFormData.pgCode = listValue[0].pKey;
							this.baseFormData.groupCode = listValue[0].groupCode;
						}
					}
				}
				
				if(this.pageCode == "machine_work_report" && res.value != undefined){
					if (res.dataType == "user") {
						var listValue = [];
						listValue = res.value;
						this.addUserInfoList(listValue)
					}
					if (res.dataType == "machine_work_report") {
						var listValue = [];
						listValue = res.value;
						if (listValue.length > 0) {
							this.baseFormData.pgCode = listValue[0].pKey;
							this.baseFormData.groupCode = listValue[0].groupCode;
						}
					}
				}
			},

			/**
			 * //添加人员信息并重新计算
			 * @param {Object} listValue
			 */
			addUserInfoList(listValue) {
				if (listValue.length > 0) {
					//判断合格数和不合格数是否为空
					if (SystemJs.systemJs.IsEmpty(this.baseFormData.number) || Number(this.baseFormData.number) <= 0) {
						SystemJs.httpUnit.uniToast("请先录入合格数")
						return;
					}
					if (SystemJs.systemJs.IsEmpty(this.baseFormData.disNumber) || Number(this.baseFormData.disNumber) <
						0) {
						SystemJs.httpUnit.uniToast("请先录入不合格数")
						return;
					}
					for (var i = 0; i < listValue.length; i++) {
						let obj = listValue[i];
						//查询是否有重复人员数据
						let select = this.userInfoList.find(v => v.userCode == obj.userCode)
						if (select != undefined) {
							continue;
						}
						//对象深拷贝，防止改变原对象数据
						let info = JSON.parse(JSON.stringify(this.userInfo));
						info.userCode = obj.userCode
						info.userName = obj.userName
						console.log(info)
						this.userInfoList.push(info);
					}

					for (var i = 0; i < this.userInfoList.length; i++) {
						var obj = this.userInfoList[i];
						//获取合格数的平均数
						var num = this.baseFormData.number / this.userInfoList.length
						//获取不合格数的平均数
						var disNum = this.baseFormData.disNumber / this.userInfoList.length
						obj.yNum = Math.floor(num * 100) / 100; //不进行四舍五入
						obj.nNum = Math.floor(disNum * 100) / 100; //不进行四舍五入
					}

					this.listInfo = this.createListItemInfo(this.infoHead, this.userInfoList);
				}
			},
			/**
			 * 创建列表item元素的显示格式
			 * @param {Object} headList
			 * @param {Object} list
			 */
			createListItemInfo(headList, list) {
				var listInfo = [];
				if (list != undefined && list.length > 0) {
					for (var i = 0; i < list.length; i++) {
						var itemObj = {};
						var itemList = [];
						var item = list[i] //每个item信息
						if (headList != undefined && headList.length > 0) {
							for (var r = 0; r < headList.length; r++) {
								var row = headList[r];
								var rowObj = {};
								var rowList = [];
								console.log(col)
								if (row != undefined && row.length > 0) {
									for (var c = 0; c < row.length; c++) {
										var col = row[c];
										var colObj = {};
										if (!SystemJs.systemJs.IsEmpty(col.type)) {
											colObj.type = col.type;
										}
										colObj.code = col.code;
										colObj.title = col.name;
										colObj.value = item[col.code];
										rowList.push(colObj);
									}
								}
								rowObj.content = rowList;
								itemList.push(rowObj);
							}
						}
						itemObj.list = itemList;
						listInfo.push(itemObj);
					}
				}
				console.log(listInfo)
				return listInfo;
			}
		}
	}
</script>

<style scoped>
	.content {
		padding: 15px;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	/* 修改form表单列样式 缩小间距*/
	.uni-forms-item {
		margin-bottom: 0px;
	}

	/* 我们需要在 style 标签上加 scoped，同时使用 deep 穿透  才能修改覆盖了子组件的样式，否则无法在父组件中修改子组件样式*/
	/deep/ .uni-forms-item.is-direction-top .uni-forms-item__label {
		padding: 0px;
	}

	/* 修改输入框不可编辑时的样式 */
	/deep/.is-disabled {
		color: #666666;
	}
</style>